// JavaScript Document
$(document).ready(function() {
  var module = $("#module").val();
  //Function to check all checkboxes
  $("#checkAll").click(function(){
    var checked_status = this.checked;
    $("input[@name=checkBoxList]").each(function() {
      this.checked = checked_status;
    });
  });

  var module_alert = $("#module").val(); //name of the module/functionality to display in alert box
	
  //Implement ignore functionality for fulfillment
  $("#edit-ignore").click(function()	{
     
    if (checkbox_values = getSelectedCheckBoxes(module_alert)) {
      //open the confirm dialog before deactivate
      openConfirmDialog("ignore", checkbox_values, 400, 125, 'Are you Sure?', 'Do you want to ignore the selected fulfillments?', "bulk");
    }
    //return without submitting the page
    return false;
  });

  //Function to hide or show the filter box
  //$("#edit-activate").click(function()	{
  $("#fullfillment-activate").click(function()	{
     
    if (checkbox_values = getSelectedCheckBoxes(module_alert)) {
      //open the confirm dialog before deactivate
      openConfirmDialog("reqactivate", checkbox_values, 400, 125, 'Are you Sure?', 'Do you want to activate the selected requests?', "bulk");
    }
    //return without submitting the page
    return false;
  });
  
  //Function to hide or show the filter box
  //$("#edit-deactivate").click(function()	{
  $("#fullfillment-deactivate").click(function()	{
    if (checkbox_values = getSelectedCheckBoxes(module_alert)) {
      //open the confirm dialog before deactivate
      openConfirmDialog("reqdeactivate", checkbox_values, 400, 125, 'Are you Sure?', 'Do you want to deactivate the selected requests?', "bulk");
    }
    //return without submitting the page
    return false;
  });
	
  //Function to hide or show the filter box
  $("#edit-archive").click(function()	{
    //Get the values of the list of checkboxes selected
    var checkbox_values = getSelectedValues();

    //return false if no checkbox is selected
    if (checkbox_values.length == 0) {
      openAlertDialog(300, 125, 'Information', 'Please select atleast one '+module);
      return false;
    }
    makeArchived(checkbox_values);
    return false;
  });
    
  $('#edit-test-search-date-from').datepicker({
    dateFormat:'mm-dd-yy'
  });
  $('#edit-test-search-date-to').datepicker({
    dateFormat:'mm-dd-yy'
  });
  $('#edit-search-date').datepicker({
    dateFormat:'mm-dd-yy'
  });
    
  
    
  //Function to implement add/edit for subjects in contactus
  $("#edit-add-new").click(function(){
    addEditRequestDialog('new', 600, 255, 'Add New Request Type');
    return false;
  });
    
});


//function to open dialog box for alert messages
function addEditRequestDialog (id, width, height, title) {
  $("#edit_reqID").val(id);
  var wid = width;
  var heit = height;
  var buttons = false;
  $('#dialog').dialog({
    autoOpen: false,
    width: wid,
    height: heit,
    bgiframe: true,
    resizable: false,
    title:title,
    modal: true,
    show: 'puff',
    close: function () {
      $(this).dialog('destroy');
    }       
  });
  $('#dialog').dialog('open');
  var h = heit;
  if(buttons){
    h = heit-95;
  }else{
    h = heit-60;
  }
  $('#dialog').css({
    'overflow-y':'auto',
    'width': (wid-40)+'px',
    'height':h+'px'
  }).show();
  addEditRequest(id);
}

//Function to get the individual testimonial to display in detail page
function addEditRequest (id) {
  $.ajax({
    type : "GET",
    url : baseurl+'fulfillment/request/actions/'+id,
    async : false,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

//Function to save requests
function saveRequests () {
  var id = $("#edit_reqID").val();
  var req_name = $.trim($("#edit-request-name").val());
  var req_desc = $("#edit-request-description").val();
	
  //code to validate the fields
  var lines = 10;
  var str = "";
  if (req_name == "") {
    str += "Please enter the Request type name";
    lines+=18;
  }
  if (req_name != "") {
    if(req_name.length > 50) {
      if(str!="")
        str+= "<br/>";
      str += "Request type name should not be more than 50 characters";
      lines+=18;
    }
  }
  if (req_desc != "") {
    if(req_desc.length > 1000) {
      if(str!="")
        str+= "<br/>";
      str += "Description should not be more than 1000 characters";
      lines+=18;
    }
  }
	
  if (str != "") {
    resize_dialog(600,225+lines);
    styleStatusMessages(str, "statusMessage", "failure");
    return;
  }
  //ends code to validate the fields
  //page loading animation
  $(".ui-dialog-buttonpane").hide();
  var content = $('#dialog').html();
  $('#dialog').html('<div style="padding-top:60px; padding-left:260px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');	
		
  $.ajax({
    type : "POST",
    url : baseurl+"fulfillment/request/actions/save",
    data : "req_id="+id+"&req_name="+req_name+"&req_desc="+req_desc,
    async : false,
    cache : false,
    success : function (msg) { 
      if (msg == "success") {
        $("#dialog").dialog("destroy");
        openAlertDialog(300, 125, 'Information', 'Request type saved successfully');
        styleStatusMessages('Request Type saved successfully.', "statusMessage", "success");
        $("#edit-request-name").val("");
        $("#edit-request-description").val("");
        //reload the subject listing
        reloadListingData($("#hid_limit").val(), 1, "", parseInt($("#hid_totalRec").val())+1, baseurl+"fulfillment/manage.requests",'page');
      }
	  else if(msg=="not_unique"){
					$('#dialog').html(content);
					$("#edit-request-name").val(req_name);
					$("#edit-request-description").val(req_desc);
					resize_dialog(600, 225 + 30);
					styleStatusMessages("Request name already exists", "statusMessage", "failure");
	 }
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
	
}

function closeDialog(testId){
  $('#dialog').dialog('destroy');
  makeArchived(testId);
}

function fulautoReply(id){
  $('#edit_reqID').val(id);
  openDialog("fulautoreply",0,700,370,"Manage Auto Reply");
}

function fulmanageautoreply(id){
  $.ajax({
    type : "GET",
    url : baseurl+'fulfillment/manage_autoreply/'+id,
    async : false,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
      if(!editor){
        editor = CKEDITOR.replace( 'edit-resp-response',{
          skin : 'v2',
          resize_enabled:false,
          enterMode: Number(2)
        });
      }else{
        if (CKEDITOR.instances['edit-resp-response']) {
          CKEDITOR.remove(CKEDITOR.instances['edit-resp-response']);
        }
        editor = null;
        editor = CKEDITOR.replace( 'edit-resp-response',{
          skin : 'v2',
          resize_enabled:false,
          enterMode: Number(2)
        });
      }
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function saveautoreply(){
  var fname = $('#edit-resp-from-name').val();
  var email = $('#edit-resp-from-email').val();
  var reply = $('#edit-resp-reply-to').val();
  var local = "EN";
  var sub = $('#edit-resp-subject').val();
  var requestTypeId = $('#edit_reqID').val();
  var resp = editor.getData();
  var str = "";
  
	if($.trim(email)!=""){
		if (!validateEmail(email)) {
			if(str!="")
				str+= "<br/>";
		
			str += "Invalid From Email Address";
			styleStatusMessages(str, "statusMessage", "failure");
			$('#dialog').scrollTop(0);
			return false;
		}
	}
	
	if($.trim(reply)!=""){
		if (!validateEmail(reply)) {
			if(str!="")
				str+= "<br/>";
			
			str += "Invalid Reply to Email Address";
			styleStatusMessages(str, "statusMessage", "failure");
			$('#dialog').scrollTop(0);
			return false;
		}
	}
  
  if($.trim(fname)=="" || $.trim(email)=="" || $.trim(reply)=="" || $.trim(local)=="" || $.trim(sub)=="" || $.trim(resp)=="" || $.trim(resp)=="<br />"){
    if($.trim(fname)=="")
      str += "From Name should not be empty";
    if($.trim(email)==""){
      if(str!="")
        str+= "<br/>";
      str += "From Email Address should not be empty";
    }if($.trim(email)!=""){
	  if (!validateEmail(email)) {
			if(str!="")
					str+= "<br/>";
			str += "Invalid From Email Address";
		}
    }if($.trim(reply)==""){
      if(str!="")
        str+= "<br/>";
      str += "Reply To should not be empty";
    }if($.trim(reply)!=""){
	  if (!validateEmail(reply)) {
			if(str!="")
					str+= "<br/>";
			str += "Invalid Reply to Email Address";
		}
    }if($.trim(local)==""){
      if(str!="")
        str+= "<br/>";
      str += "Language should not be empty";
    }
    if($.trim(sub)==""){
      if(str!="")
        str+= "<br/>";
      str += "Subject should not be empty";
    }
    if($.trim(resp)=="" || $.trim(resp)=="<br />"){
      if(str!="")
        str+= "<br/>";
      str += "Content should not be empty";
    }
    styleStatusMessages(str, "statusMessage", "failure");
    $('#dialog').scrollTop(0);
    return false;
  }else{
		
    $('#dialog').html('<div style="padding-top:90px; padding-left:300px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." title="Loading... Please Wait !!!" border="0"></div>');
		
    $.ajax({
      type : "POST",
      url : baseurl+'fulfillment/manage_autoreply/save',
      data: 'fname='+fname+"&email="+email+"&reply="+reply+"&local="+local+"&subject="+sub+"&resp="+resp+"&reqid="+requestTypeId,
      async : false,
      cache : false,
      success : function (msg) {
        if(msg=="Success"){
          $('#dialog').dialog('destroy');
          openAlertDialog(300, 125, 'Information', 'Auto Reply saved successfully');
        }
      },
      error : function (res) {
        handleRequestError(res);
      }
    });
  }
  return false;
}


function deleteFulfillment(id){
	
  $.ajax({
    type : "POST",
    url : baseurl+"fulfillment/actions/ignore",
    data : "checkbox_values="+id,
    async : false,
    cache : false,
    success : function (msg) {
      if (msg == "success") {
        var reduce = parseInt($("#hid_totalRec").val()) - 1;
        var limit = parseInt($("#hid_limit").val());
        var pageno = parseInt($("#hid_pageno").val());
        var mod = reduce % limit;
        //reload the listing to apply the effect
        reloadListingData (10, pageno, "next", reduce, baseurl+"fulfillment", "page");
        closeDialog(id);
      }
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

//Function to ignore the selected messages
function ignoreArchiveMessages (ok, fn, id, mode) { 
  var cnt = 0;
  if (ok) {
    $(ok).dialog('destroy');
  }
  //Prepare the status message
  if (fn == "ignore") {
    var str = "Ignored";
  }
  else if (fn == "archive") {
    var str = "Archived";
  }

  //AJAX call to update the status of the messages
  $.ajax({
    type : "POST",
    url : baseurl+"fulfillment/actions/"+(fn == "ignore" ? fn : "archive"),
    data : "checkbox_values="+id,
    async : false,
    cache : false,
    success : function (msg) {
			$("#dialog").dialog("destroy");
      if (msg == "success") {
        if (mode == "single") {
          $("#listingOperations"+id).html(str);
          $("#Activate"+id).show();
          cnt++;
        }
        else if (mode == "bulk") {
          $('input[@name=checkBoxList]:checked').each(function(){
            $("#listingOperations"+($(this).val())).html(str);
            this.checked = false;
            cnt++;
          });
          if ($("#checkAll")) {
            $("#checkAll").attr('checked', false);
          }
        }
        //code to retail the same page after reloading
        var reduce = parseInt($("#hid_totalRec").val()) - cnt;
        var limit = parseInt($("#hid_limit").val());
        var pageno = parseInt($("#hid_pageno").val());
        var mod = reduce % limit;
        if (mod == 0) {
          if (pageno > 1) {
            pageno = pageno - 1;
          }
          else {
            pageno = pageno;
          }
        }
				
        //reload the listing to apply the effect
        reloadListingData (10, pageno, "", reduce, baseurl+"fulfillment", "page");
      }
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

//Function to implement the filter action for messages
function applyMessageFilterAction (pageno, locate) { 
  //prepare the field values for filtering
  var name = $.trim($("#edit-test-search-name").val());
  var email = $("#edit-test-search-email").val();
  var requesttype = $("#edit-test-search-requesttype").val();
  var date_from = $.trim($("#edit-test-search-date-from").val());
  var status = $.trim($("#edit-test-search-status").val());
  var sort = $('#hid_sort').val();
	
  //page loading animation
  pagination_loading("page");
	
  $.ajax({
    type : "POST",
    url : baseurl+"fulfillment/actions/filter"+(locate=='archived'?'/archived':''),
    data : "name="+name+"&email="+email+"&requesttype="+requesttype+"&date_from="+date_from+"&status="+status+(pageno>1?'&page_no='+pageno:'')+(sort!=""?"&sorting="+sort:""),
    async : false,
    cache : false,
    success : function (msg) {  //alert(msg);
      $("#listingResultset").html(msg);
      var limit = $('#hid_limit').val();
      var page = pageno;
      var counter = $('#hid_totalRec').val();
			
      //create pagination links through AJAX
      create_pagination_links(counter, page, limit, locate, 'applyMessageFilterAction','page');
    },
	error : function (res) {
      handleRequestError(res);
    }
  });
}

//Function to implement the filter action for subjects
function applyRequestsFilterAction (pageno, locate) { 
  //prepare the field values for filtering
  var search_request = $("#edit-search-request").val();
  var search_desc = $.trim($("#edit-search-desc").val());
  var search_username = $.trim($("#edit-search-username").val());
  var search_status = $("#edit-request-status").val();
  var search_date = $.trim($("#edit-search-date").val());
	var sort = $('#hid_sort').val();
   						
  //page loading animation
  pagination_loading("page");
	
  $.ajax({
    type : "POST",
    url : baseurl+"fulfillment/request/actions"+(locate=='archived'?'/archived':(locate=='manage.requests'?'/manage.requests':'')),
    data : "search_request="+search_request+"&search_username="+search_username+"&search_desc="+search_desc+"&search_date="+search_date+"&search_status="+search_status+(pageno>1?'&page_no='+pageno:'')+(sort!=""?"&sorting="+sort:""),
    async : false,
    cache : false,
    success : function (msg) { //alert(msg);
			
      $("#listingResultset").html(msg);
      var limit = $('#hid_limit').val();
      var page = pageno;
      var counter = $('#hid_totalRec').val();
      //create pagination links through AJAX
      create_pagination_links(counter, page, limit, locate, 'applyRequestsFilterAction','page');
    },
	error : function (res) {
      handleRequestError(res);
    }
  });
}

//Function to create pagination links while filtering
function create_pagination_links (counter, page, limit, locate, fn) {
  var str = "";
  var to = page*limit;
	
  str += '<span>Showing <b>'+(counter>0?(page-1)*limit+1:0)+'</b> to <b>'+(to>counter?counter:to)+'</b> of <b>'+counter+'</b></span>';
  if (page > 1) {
    str += '<a href="javascript:void(0)" onclick = "'+fn+'('+(page-1)+',\''+locate+'\')" class="red"><< Previous</a>';
  }
  if (to < counter) {
    str += '<span class="red"> |</span><a href="javascript:void(0)" onclick = "'+fn+'('+(page+1)+',\''+locate+'\')" class="red">Next >></a>';
  }

  $("#pagingdivtop").html(str);
  $("#pagingdivbottom").html(str);
}

//function to activate or deactivate subjects
function activateDeactivateRequests (ok, fn, id, mode) { 
  var content = $("#dialog").html();
  if (ok && ok != "detail") {
    //Page loading animation
    $('#dialog').html('<div style="padding-top: 10px; padding-left: 150px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  }
  else {
    //Page loading animation
    $('#dialog').html('<div style="padding-top: 25px; padding-left: 200px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  }
  //AJAX call to update the status of the messages
  $.ajax({
    type : "POST",
    url : baseurl+"fulfillment/request/actions/"+(fn == "reqactivate" ? fn : "reqdeactivate"),
    data : "checkbox_values="+id,
    async : false,
    cache : false,
    success : function (msg) {
      if (msg == "success") {
        $("#dialog").dialog("destroy");
        if (fn == "reqdeactivate" && mode == "single") {
          $("#Deactivate"+id).hide();
          $("#Activate"+id).show();
          $("#SubjectStatus"+id).html("Inactive");
        }
        else if (fn == "reqactivate" && mode == "single") {
          $("#Deactivate"+id).show();
          $("#Activate"+id).hide();
          $("#SubjectStatus"+id).html("Active");
        }
        else if (fn == "reqdeactivate" && mode == "bulk") {
          $('input[@name=checkBoxList]:checked').each(function(){
            $("#Deactivate"+($(this).val())).hide();
            $("#Activate"+($(this).val())).show();
            $("#SubjectStatus"+($(this).val())).html("Inactive");
            this.checked = false;
          });
          if ($("#checkAll")) {
            $("#checkAll").attr('checked', false);
          }
        }else if (fn == "reqactivate" && mode == "bulk") {
          $('input[@name=checkBoxList]:checked').each(function(){
            $("#Deactivate"+($(this).val())).hide();
            $("#Activate"+($(this).val())).show();
            $("#SubjectStatus"+($(this).val())).html("Active");
            this.checked = false;
          });
          if ($("#checkAll")) {
            $("#checkAll").attr('checked', false);
          }
        }
        if (ok == "detail") {
          $("#dialog").html(content);
          if (fn == "activate") {
            $("#deactivateSubjectBtn").val("Deactivate");
            $("#subjectStatus").val("Active");
            $("#statusCodePopup").html("Active");
          }
          else {
            $("#deactivateSubjectBtn").val("Activate");
            $("#subjectStatus").val("InActive");
            $("#statusCodePopup").html("InActive");
          }
          loadRequestTypeFunctions(id);
          $("#dialog").dialog("destroy");
          openAlertDialog(300, 125, 'Information', 'Request type Status changed successfully');
        }
      }
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function filterdata_fulfillment(){
  var name = $.trim($("#edit-test-search-name").val());
  var email = $("#edit-test-search-email").val();
  var requesttype = $("#edit-test-search-requesttype").val();
  var date_from = $.trim($("#edit-test-search-date-from").val());
  var status = $.trim($("#edit-test-search-status").val());
  var data = "";
  if($.trim(name)!=""){
    data+="&name="+name;
  }
  if($.trim(email)!=""){
    data+="&email="+email;
  }
  if($.trim(requesttype)!=""){
    data+="&requesttype="+requesttype;
  }
  if($.trim(status)!="" && status != "ANY"){
    data+="&status="+status;
  }
  if($.trim(date_from)!=""){
    data+="&date_from="+date_from;
  }
  return data;
}

function filterdata_requests(){
  var search_request = $("#edit-search-request").val();
  var search_desc = $.trim($("#edit-search-desc").val());
  var search_username = $.trim($("#edit-search-username").val()); //JJ
  var search_status = $("#edit-request-status").val();
  var search_date = $.trim($("#edit-search-date").val());
	
  var data = "";
  if($.trim(search_request)!=""){
    data+="&search_request="+search_request;
  }
  if($.trim(search_desc)!=""){
    data+="&search_desc="+search_desc;
  }
  if($.trim(search_username)!=""){
    data+="&search_username="+search_username;
  }
  if($.trim(search_status)!=""){
    data+="&search_status="+search_status;
  }
  if($.trim(search_date)!=""){
    data+="&search_date="+search_date;
  }
		
  return data;
}

//Function to get the individual message to display in detail page
function requestTypeDetails (id) {
  $("#edit_subID").val(id);
  $.ajax({
    type : "GET",
    url : baseurl+'fulfillment/request/actions/view/'+id,
    async : true,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
      loadRequestTypeFunctions(id);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function loadRequestTypeFunctions (id) {
  $('#edit_reqID').val(id);
  //ignore message in detail page
  $("#deactivateSubjectBtn").click(function() {
    if ($("#subjectStatus").val() == "Active") {
      var status_str = "reqdeactivate";
      var str_con = "deactivate";
    }
    else {
      var status_str = "reqactivate";
      var str_con = "activate";
    }
    openConfirmBox(function(){
      $("#alertdialog").dialog("destroy");
      activateDeactivateRequests ("detail", status_str, id, "single");
    }, 300, 100, "Confirm "+str_con, "Do you want to "+str_con+" this request?");
  });
  //manage auto reply in detail page
  $("#manageAutoReplyBtn").click(function() {
    reopen_dialog(750, 450, "Manage Auto Reply");
    fulmanageautoreply(id);
  });
  //edit message in detail page
  $("#EditSubjectBtn").click(function() {
    reopen_dialog(600, 250, "Edit Request Type");
    addEditRequest(id);
  });	
}